package com.db.service.bank;

import com.db.domain.bank.Bank;
import com.db.exceptions.NotEnoughFundsException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class BankServer {

    public static final int PORT_NUMBER = 7777;

    public void startServer() {
        try (ServerSocket serverSocket = new ServerSocket(PORT_NUMBER);
             Socket socket = serverSocket.accept()
        ){
            try (
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())
                ) {
                while(true) {
                    String queue = dataInputStream.readUTF();
                    String answer;
                    switch (queue) {
                        case "gb":
                            answer = BankApplication.getBalances();
                            break;
                        case "mb" :
                            try {
                                BankApplication.modifyBank();
                                answer = "Bank was modified successfully.";
                            } catch (NotEnoughFundsException e) {
                                answer = "Not enough money on account. " + e.getAccount() + " The overdraft equals " + e.getAllowedBalance() +
                                        " Please, recharge your balance.";
                            }
                            break;
                        case "cc" :
                            answer = "Count of clients " + BankApplication.getCountOfClients();
                            break;
                        default:
                            answer = "error command";
                    }
                    dataOutputStream.writeUTF(answer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
